package com.lcxw.hxzbapi.controller.roomcontroller;

import com.alibaba.fastjson.JSONObject;
import com.lcxw.hxzbcommon.entity.ErrorCode;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.lcxw.hxzbapi.entity.pojo.YwpdMember;
import com.lcxw.hxzbapi.entity.pojo.YwpdRoom;
import com.lcxw.hxzbapi.entity.requestBean.CreateRoomRequestParam;
import com.lcxw.hxzbapi.entity.response.Response;
import com.lcxw.hxzbapi.service.YwpdMemberService;
import com.lcxw.hxzbapi.service.YwpdRoomService;
import com.lcxw.hxzbcommon.common.IdGenerator;
import com.lcxw.hxzbcommon.common.StringUtil;
import com.lcxw.hxzbcommon.common.qiniu.Client;
import com.lcxw.hxzbcommon.common.qiniu.RoomConfig;
import com.lcxw.hxzbcommon.common.qiniu.Hub;
import com.lcxw.hxzbcommon.common.qiniu.PiliException;

@RestController
@RequestMapping("/api/room")
@CrossOrigin
@Validated
public class RoomConfigController {

    private Logger logger = LoggerFactory.getLogger(RoomConfigController.class);

    @Resource
    YwpdRoomService ywpdRoomService;

    @Resource
    RoomRealization roomRealization;

    @Resource
    YwpdMemberService ywpdMemberService;

    private IdGenerator idGenerator = new IdGenerator(1, 1);

    /**
     * 1、创建房间接口
     */
    @PostMapping("/create")
    public Response createRoom(@Valid @RequestBody CreateRoomRequestParam requestParams) {

        long userId = requestParams.getUserId();

        Response response = new Response();
        YwpdRoom ywpdRoom = new YwpdRoom();

        long roomId = idGenerator.nextId();
        ywpdRoom.setRoomId(roomId);
        ywpdRoom.setCreatTime(StringUtil.getDateTime());
        ywpdRoom.setLiveStatus(0);

        //开始在七牛云创建直播流
        //初始化client
        Client cli = new Client(RoomConfig.ACCESS_KEY, RoomConfig.SECRET_KEY);
        //初始化Hub
        Hub hub = cli.newHub(RoomConfig.HUB);
        try {
            hub.create(roomId + "");
        } catch (PiliException e) {
            e.printStackTrace();
            return Response.common(logger, "创建七牛云直播流失败", ErrorCode.LOSE_EFFICACY, "创建直播流失败，请检查七牛云欠费情况。", null);
        }

        //设置房间的推拉流地址
        ywpdRoom.setPullUrl(RoomConfig.getPullUrl(roomId));
        ywpdRoom.setPushUrl(RoomConfig.getPushUrl(roomId));

        String roomName;
        try {
            if (StringUtil.isEmpty(requestParams.getRoomName())) {
                YwpdMember ywpdMember = ywpdMemberService.selectYwpdMemberByUserId(userId);
                String nickName = ywpdMember.getNickName();
                roomName = nickName+"的直播间";
                ywpdRoom.setRoomName(roomName);
            } else {
                roomName = requestParams.getRoomName();
                ywpdRoom.setRoomName(roomName);
            }

            ywpdRoomService.createYwpdRoom(ywpdRoom);
            response.setDesc("create room success");
            Map<String, Object> data = new LinkedHashMap<>();
            data.put("roomId", roomId);
            data.put("roomName", roomName);

            response.setData(data);
        } catch (Exception e) {
            e.printStackTrace();
            logger.warn("create room failed,db operate failed");
            response.setCode(ErrorCode.INTERNAL_ERROR);
            response.setDesc("数据库操作失败。");
            return response;
        }

        return response;
    }

    /**
     *  2、获取我的房间接口
     */
    @PostMapping("/get")
    public Response queryRoom(@RequestBody JSONObject requestParams) {
        logger.info("user {} want to get room", requestParams.getString("userId"));
        long userId = Long.parseLong(requestParams.getString("userId"));
        JSONObject data;
        try {
            data = roomRealization.getMyRoomInfo(userId);
        } catch (Exception e) {
            return Response.dbFail(logger,"get my room info");
        }

        if (null != data.getInteger("realNameAuth") && 0 == data.getInteger("realNameAuth")){
            return Response.common(logger,"该用户还未实名认证",ErrorCode.INVALID_PARAM,"该用户还未实名认证",null);
        }
        return Response.ok(data);
    }

    /**
     * 3、设置房间接口
     */
    @PostMapping("/set")
    public Response getRoom(@RequestBody JSONObject requestParams) {
        logger.info("{} want to set room {}.", requestParams.getString("userId"),
            requestParams.getString("roomId"));

        long roomId = Long.parseLong(requestParams.getString("roomId"));
        long userId = Long.parseLong(requestParams.getString("userId"));

        String roomType = requestParams.getString("roomType");
        if (!"paipai".equals(roomType) && !"fullVideo".equals(roomType) && !"voice"
            .equals(roomType)) {
            return Response.wrongParam(logger, "roomType");
        }

        Response response = new Response();
        YwpdRoom ywpdRoom;

        try {
            ywpdRoom = ywpdRoomService.selectRoomByRoomId(roomId);
            if (userId != ywpdRoom.getUserId()) {
                logger.warn("userId {} and roomId {} doesn't match.", userId, roomId);
                response.setCode(ErrorCode.INVALID_REQ);
                response
                    .setDesc("userId {" + userId + "} and roomId {" + roomId + "} doesn't match.");
                return response;
            }

            if (!StringUtil.isEmpty(requestParams.getString("roomName"))) {
                ywpdRoom.setRoomName(requestParams.getString("roomName"));
            }
            if (!StringUtil.isEmpty(requestParams.getString("roomNotice"))) {
                ywpdRoom.setRoomNotice(requestParams.getString("roomNotice"));
            }

            ywpdRoom.setRoomType(roomType);
            ywpdRoomService.updateRoom(ywpdRoom);
            response.setDesc("success");

            logger.info("user {} set roomInfo success", userId);

        } catch (Exception e) {
            e.printStackTrace();
            return Response.dbFail(logger, "select room by roomId");
        }

        return response;
    }


}
